package com.tools.xxf.updatelib.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.blankj.utilcode.util.LogUtils;
import com.tools.xxf.updatelib.updateapp.UpdateService;

import java.io.File;

/**
 * TODO
 *
 * @author XXF
 *         Create Time : 2017/12/7 14:18
 */
public class ApkUtils {

    public static Intent installIntent(Context context, String path) {
        LogUtils.d("installIntent: " +
                path
                + "==" + new File(path).length());

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri fileUri = FileProvider.getUriForFile(context, getFileProviderAuthority(context),
                    new File(path));
            intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android" +
                    ".package-archive");
        }
        return intent;
    }

    /**
     * 获取FileProvider的auth
     */
    public static String getFileProviderAuthority(Context context) {
        try {
            for (ProviderInfo provider : context.getPackageManager().getPackageInfo(context
                    .getPackageName(), PackageManager.GET_PROVIDERS).providers) {
                if (FileProvider.class.getName().equals(provider.name) && provider.authority
                        .endsWith(".update_app.file_provider")) {
                    return provider.authority;
                }
            }
        } catch (PackageManager.NameNotFoundException ignore) {
        }
        return null;
    }

    public static Intent webLauncher(String downloadUrl) {
        Uri download = Uri.parse(downloadUrl);
        Intent intent = new Intent(Intent.ACTION_VIEW, download);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    public static String getSaveFileName(String downloadUrl) {
        if (downloadUrl == null || TextUtils.isEmpty(downloadUrl) || downloadUrl.lastIndexOf("&")
                <= 0 || downloadUrl.lastIndexOf("&") + 1 > downloadUrl.length()) {
            return System.currentTimeMillis() + ".apk";
        }
        return downloadUrl.substring(downloadUrl.lastIndexOf("&") + 1);
    }

    public static File getDownloadDir(Context context,String storeDir, int updateTotalSize) {
        File downloadDir = null;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED) && SDCardHelper.getSDCardAvailableSize() > ((float)
                updateTotalSize / 1024 / 1024)) {
            if (!TextUtils.isEmpty(storeDir) ) {
                downloadDir = new File(Environment.getExternalStorageDirectory(), storeDir);
            } else {
                downloadDir = new File(context.getExternalCacheDir(), "update");
            }
        } else if (SDCardHelper.getAvailableInternalMemorySize() > ((float) updateTotalSize /
                1024 / 1024)) {
            downloadDir = context.getFilesDir();
        }
        if (downloadDir != null && !downloadDir.exists()) {
            //noinspection ResultOfMethodCallIgnored
            downloadDir.mkdirs();
        }
        return downloadDir;
    }

}
